# -*- coding: utf-8 -*-
from rest_framework import serializers
from .models import Product, GoodCategory, GoodBrand, IndexCarouselGood, CategoryIndexAD, \
    HotSearchWords, Good, Source, Attribute, SPG, Param
from operation.models import UserFav
import snowflake.client


class HotSearchSerializer(serializers.ModelSerializer):
    class Meta:
        model = HotSearchWords
        fields = '__all__'


class SpgSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPG
        fields = '__all__'


class AttributeSerializer(serializers.ModelSerializer):
    # attribute_spg = SpgSerializer()
    class Meta:
        model = Attribute
        fields = '__all__'


class ParamSerializer(serializers.ModelSerializer):
    class Meta:
        model = Param
        fields = '__all__'


class SpgAttributeSerializer(serializers.ModelSerializer):
    attribute_spg = AttributeSerializer(many=True)
    param_spg = AttributeSerializer(many=True)

    class Meta:
        model = SPG
        fields = '__all__'


# class GoodCarouselImageSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = GoodCarouselImage
#         fields = ('image',)


class GoodCategorySerializer3(serializers.ModelSerializer):
    class Meta:
        model = GoodCategory
        fields = '__all__'


class GoodCategorySerializer2(serializers.ModelSerializer):
    sub_cat = GoodCategorySerializer3(many=True)

    class Meta:
        model = GoodCategory
        fields = '__all__'


class GoodCategorySerializer(serializers.ModelSerializer):
    sub_cat = GoodCategorySerializer2(many=True)

    class Meta:
        model = GoodCategory
        fields = '__all__'


class SecondGoodCategorySerializer(serializers.ModelSerializer):
    sub_cat = GoodCategorySerializer2(many=True)

    class Meta:
        model = GoodCategory
        fields = '__all__'


class GoodParamSerializer(serializers.ModelSerializer):
    class Meta:
        model = Good
        fields = '__all__'


class ParamProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['title', 'id']  # 可以用 [] 进行指定


class GoodSerializer(serializers.ModelSerializer):
    # product = ParamProductSerializer()
    # 单独写一个方法 进行获取 be_product 的标题
    be_product = ParamProductSerializer()

    class Meta:
        model = Good
        fields = ['be_product', 'params', 'sold_price', 'cover', 'cover', 'desc', 'good_num']


class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodBrand
        fields = ['id', 'image', 'zh_name', 'en_name']  # 可以用 [] 进行指定


class SourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Source
        fields = "__all__"


class IndexFilterGoodSerializer(serializers.ModelSerializer):
    # 后期可以优化成考拉 直接可以swiper的那种
    # params = GoodParamSerializer(many=True)
    goods = GoodSerializer(many=True)
    category = GoodCategorySerializer3()
    brand = BrandSerializer()
    spg = SpgSerializer()
    source = SourceSerializer()

    # Product.objects.create()
    #
    # for item in Product.objects.all():
    #     print(item.__dict__)

    class Meta:
        model = Product
        fields = ['id', 'title', 'fav_num', 'category', 'brand', 'goods', 'images', 'min_price', 'max_price',
                  'total_sold', 'update_time', 'source', 'desc', 'sn', 'sort', 'pic', 'spg', 'is_delete', 'is_new',
                  'is_recommend']


class IndexProductSerializer(serializers.ModelSerializer):
    """
    序列化 产品
    """

    # 继承 Serializer 需要手动书写
    # id = serializers.IntegerField(read_only=True)
    # name = serializers.CharField(max_length=100)
    # category = GoodCategorySerializer()

    # images = GoodCarouselImageSerializer(many=True)
    goods = GoodSerializer(many=True)

    # 'images', 'desc',
    class Meta:
        model = Product
        fields = ['id', 'title', 'goods', 'pic', 'min_price']
        # fields = '__all__'
        # fields = ['category', 'id', 'name', 'cover', 'sold_num', 'good_desc', 'shop_price', 'market_price', 'images']


class UpdateGoodSerializer(serializers.ModelSerializer):
    be_product = serializers.PrimaryKeyRelatedField(queryset=Good.objects.all(), required=True)

    class Meta:
        model = Good
        fields = "__all__"  # 可以用 [] 进行指定


class ProductSerializer(serializers.ModelSerializer):
    # 继承 Serializer 需要手动书写
    # id = serializers.IntegerField(read_only=True)
    # name = serializers.CharField(max_length=100)
    # category = GoodCategorySerializer()
    # images = GoodCarouselImageSerializer(many=True)
    # params = GoodParamSerializer(many=True)
    # brand = BrandSerializer()
    is_col = serializers.SerializerMethodField()

    def get_is_col(self, obj):
        user = self.context['request'].user
        if user == 'AnonymousUser':
            return False

        is_exist = UserFav.objects.filter(user__username=user)

        if not is_exist:
            return False

        if is_exist.filter(product__id=obj.id):
            return True

    class Meta:
        model = Good
        fields = "__all__"  # 可以用 [] 进行指定

    # 取来自view验证的数据，创建对象
    # def create(self, validated_data):
    #     return Good.objects.create(**validated_data)


class CreateGoodSerializer(serializers.ModelSerializer):
    class Meta:
        model = Good
        fields = ['params', 'good_num', 'cover', 'sold_price', 'weight']


class GoodSerializerUpdate(serializers.ModelSerializer):
    class Meta:
        model = Good
        fields = ['params', 'good_num', 'cover', 'sold_price', 'weight']


from drf_writable_nested.serializers import WritableNestedModelSerializer


class CreateProductSerializer(serializers.ModelSerializer):
    goods = CreateGoodSerializer(many=True)
    category = serializers.PrimaryKeyRelatedField(queryset=GoodCategory.objects.filter(category_type=3), required=True)
    brand = serializers.PrimaryKeyRelatedField(queryset=GoodBrand.objects.all(), required=True)
    spg = serializers.PrimaryKeyRelatedField(queryset=SPG.objects.all(), required=True)

    def create(self, validated_data):
        print(validated_data)
        goods = validated_data.pop('goods')

        product = Product.objects.create(**validated_data)
        for good in goods:
            good['sku_id'] = self.get_snowflake_uuid()
            Good.objects.create(be_product=product, **good)

        return product

    def get_snowflake_uuid(self):
        guid = snowflake.client.get_guid()
        return guid

    # 先经过这里在 create
    def validate(self, attrs):
        if 'sn' in attrs:
            return attrs

        attrs['sn'] = self.get_snowflake_uuid()
        return attrs

    class Meta:
        model = Product
        fields = ['brand', 'category', 'spg', 'images', 'pic', 'title', 'desc',
                  'params', 'attrs', 'detail', 'unit', 'goods', 'is_delete', 'is_new', 'is_recommend',
                  ]


class UpdateCarousel(serializers.ModelSerializer):
    class Meta:
        model = IndexCarouselGood
        fields = ['id', 'name']


class UpdateProductSerializer(serializers.ModelSerializer):
    goods = GoodSerializerUpdate(many=True)
    # carousel_product = UpdateCarousel(many=True)
    category = serializers.PrimaryKeyRelatedField(queryset=GoodCategory.objects.filter(category_type=3), required=True)
    brand = serializers.PrimaryKeyRelatedField(queryset=GoodBrand.objects.all(), required=True)
    spg = serializers.PrimaryKeyRelatedField(queryset=SPG.objects.all(), required=True)

    def update(self, instance, validated_data):
        print(validated_data)
        goods = validated_data.get('goods', [])

        # goods 为空直接返回  不要删除原有数据库
        # 不为零  要 pop出来  nested嵌套属性 提前处理
        # 不为0 删除
        if len(goods) != 0:
            for good in Product.objects.get(id=instance.id).goods.all():
                good.is_delete = 1
                good.save()

            goods = validated_data.pop('goods')
            for good in goods:
                good['sku_id'] = self.get_snowflake_uuid()
                Good.objects.create(be_product=instance, **good)

        # 更新数据
        for key, value in validated_data.items():
            setattr(instance, key, value)
        instance.save()

        return instance

    def get_snowflake_uuid(self):
        guid = snowflake.client.get_guid()
        return guid

    class Meta:
        model = Product
        fields = ['brand', 'category', 'spg', 'images', 'pic', 'title', 'desc', 'carousel',
                  'params', 'attrs', 'detail', 'unit', 'goods', 'is_delete', 'is_new', 'is_recommend']


class CarouselSerializer(serializers.ModelSerializer):
    class Meta:
        model = IndexCarouselGood
        fields = "__all__"


class ProductSerializerOne(serializers.ModelSerializer):
    # 继承 Serializer 需要手动书写
    # id = serializers.IntegerField(read_only=True)
    # name = serializers.CharField(max_length=100)
    # category = GoodCategorySerializer()
    # images = GoodCarouselImageSerializer(many=True)
    # params = GoodParamSerializer(many=True)
    # brand = BrandSerializer()
    # carousel_product = CarouselSerializer(many=True)
    goods = GoodParamSerializer(many=True)
    category = GoodCategorySerializer3()
    brand = BrandSerializer()
    spg = SpgAttributeSerializer()
    is_col = serializers.SerializerMethodField()

    def get_is_col(self, obj):
        user = self.context['request'].user
        if user == 'AnonymousUser':
            return False

        is_exist = UserFav.objects.filter(user__username=user)

        if not is_exist:
            return False

        if is_exist.filter(product__id=obj.id):
            return True

    class Meta:
        model = Product
        fields = '__all__'
        # fields = ['id', 'category', 'brand', 'sn', 'title', 'fav_num', 'goods', 'is_col']  # 可以用 [] 进行指定

    # 取来自view验证的数据，创建对象
    # def create(self, validated_data):
    #     return Good.objects.create(**validated_data)


class CarouselGoodSerializer(serializers.ModelSerializer):
    """
    轮播商品序列化
    """

    class Meta:
        model = IndexCarouselGood
        fields = "__all__"  # 可以用 [] 进行指定


class HotWordsSerializer(serializers.ModelSerializer):
    class Meta:
        model = HotSearchWords
        fields = "__all__"


class CategoryBrandAdSerializer(serializers.ModelSerializer):
    """
    商品下属商标和广告序列化
    # 需要的数据
    品牌
    前八个商品
    广告
    """
    # sub_cat = GoodCategorySerializer3(many=True)
    banner_product = serializers.SerializerMethodField()
    brand_info = serializers.SerializerMethodField()

    # banner = BrandSerializer(many=True)
    # goods = serializers.SerializerMethodField()
    # ad_goods = serializers.SerializerMethodField()
    def get_brand_info(self, obj):
        brand = GoodBrand.objects.filter(category_id=obj.id).order_by('id')[:5]
        # brand = Product.objects.filter(brand_id=obj.id).order_by('id')
        return BrandSerializer(brand, many=True, context={'request': self.context['request']}).data

    def get_banner_product(self, obj):
        # print(obj)
        from django.db.models import Q
        # GoodCategory.objects.filter()
        products = Product.objects.filter(category__parent_category__parent_category_id=obj.id).order_by('id')[:8]
        # products = GoodCategory.objects.filter(Q(category_type=1) & Q(is_banner=1)).product_set.order_by('-id')[:8]
        return IndexProductSerializer(products, many=True, context={'request': self.context['request']}).data

    # def get_goods(self, obj):
    #     from django.db.models import Q
    #     all_goods = Product.objects.filter(Q(category_id=obj.id) | Q(category__parent_category_id=obj.id) | Q(
    #         category__parent_category__parent_category_id=obj.id))[:8]
    #     return IndexGoodSerializer(all_goods, many=True, context={'request': self.context['request']}).data
    #
    # def get_ad_goods(self, obj):
    #     # print(obj.id)
    #     all_goods = Product.objects.filter(category__parent_category__parent_category_id=obj.id)
    #     # print('11'*100)
    #     # print(all_goods)
    #     return IndexGoodSerializer(all_goods, many=True, context={'request': self.context['request']}).data
    # 反查
    # ad_goods = {}
    # is_exist = IndexAD.objects.filter(category_id=obj.id)
    # if is_exist:
    #     goods = is_exist[0]
    #     return GoodSerializer(goods.good, many=False, context={'request': self.context['request']}).data

    class Meta:
        model = GoodCategory
        fields = "__all__"  # 可以用 [] 进行指定
